#! /usr/bin/python 
# -*- coding: utf-8 -*-

import sqlite3
import sys
import os
import urllib2
import time
import getopt
from datetime import datetime

def Operate(dbFile,keywordFile,outputFile,projectName,projetVersion,startDate,endDate):
	wordList=["bug","issue","problem","fixed","fix","landed","land","solved","solve","corrected","correct","tweaked","tweak"]
	
	startDate = datetime.strptime(startDate, '%Y-%m-%d')
	endDate = datetime.strptime(endDate, '%Y-%m-%d')
	
	filename= "%s" % (keywordFile)
	f=open(filename, 'r')
	lines= f.readlines()
	f.close()
	for line in lines:
		if len(line.split('\n')[0]) > 0 :
			wordList.append(line.split('\n')[0])


	conn = sqlite3.connect(dbFile)
	c = conn.cursor()
	c.execute("SELECT revisionNo,commitMessage FROM commitTable where projectName=? and projectVersion=? and commitDate between ? and ?", (projectName,projetVersion,str(startDate),str(endDate)))

	commitDict={}

	for row in c:
		commitDict[row[0]]=row[1]


	#reportFileName = "%s_%s" % ("BuggyFiles",int(time.time()))
	reportFileName = "%s" % (outputFile)
	report= open(reportFileName,'w')

	for commitNo,commitMessage in commitDict.iteritems():
		for word in wordList:
			if word in commitMessage:
				c.execute("SELECT filePath FROM fileTable WHERE revisionNo=? and projectName=? and projectVersion=?",(commitNo,projectName,projectVersion))
				for row in c:
					report.write("%s\n" % (row[0]))
				break
	

def ShowHelp():
    print "Usage: defectMatch.py --dbfile [sqlite db file path] --keywordfile [keyword file path] --projectname [name] --projectversion [version] --startdate [YYYY-MM-DD] --endDate [YYYY-MM-DD]  --outputfile [output file path (optional)]"    
    sys.exit(0)

if __name__ == "__main__":
	dbFile = None
	outputFile = None
	keywordFile= None
	projectName=None
	projectVersion=None;
	startDate=None;
	endDate=None;
	try:
        	opts, args = getopt.getopt(sys.argv[1:],"f1:f2:f3:f4:f5:f6:f7",["dbfile=","keywordfile=","projectname=","projectversion=","startdate=","enddate=","outputfile="])
        	for opt, arg in opts:
			if opt in ("-f1", "--dbfile"):
				dbFile = arg
			elif opt in ("-f2", "--keywordfile"):
				keywordFile = arg
			elif opt in ("-f3", "--projectname"):
				projectName = arg
			elif opt in ("-f4", "--projectversion"):
				projectVersion = arg
			elif opt in ("-f5", "--startdate"):
				startDate = arg
			elif opt in ("-f6", "--enddate"):
				endDate=arg
			elif opt in ("-f7", "--outputfile"):
				outputFile = arg
		if len(sys.argv) == 1:
            		ShowHelp()
		elif not dbFile:
			print "DB File was not specified"
			ShowHelp()
		elif not keywordFile:
			print "Keyword File was not specified"
			ShowHelp()
		elif not projectName:
			print "Project name was not specified"
			ShowHelp()
		elif not projectVersion:
			print "Project version was not specified"
			ShowHelp()
		elif not startDate:
			print "Start date was not specified"
			ShowHelp()
		elif not endDate:
			print "End date was not specified"
			ShowHelp()
		elif not outputFile:
			outputFile="BuggyFiles"
			Operate(dbFile,keywordFile,outputFile,projectName,projectVersion,startDate,endDate)
		else:
			Operate(dbFile,keywordFile,outputFile,projectName,projectVersion,startDate,endDate)
	except getopt.GetoptError:
        	ShowHelp()

